<template>
  <div class="container">
    <el-form ref="memberBindRef" :model="cardForm" :label-width="110" :rules="rules" status-icon
      style="width: 70%; padding-left: 10%;">
      <!-- 学员选择 -->
      <el-form-item label="学员">
        <el-select v-model="cardForm.memberId" placeholder="-请输入名字或手机号码搜索-" filterable remote reserve-keyword
          :remote-method="remoteMethod" :loading="loading" automatic-dropdown>
          <!-- ✅ 添加这个属性实现点击即展开 -->

          <template #header>
            <el-row>
              <el-col :span="5">
                <h3 style="padding-left: 45px;">ID</h3>
              </el-col>
              <el-col :span="7">
                <h3 style="padding-left: 16px;">姓名</h3>
              </el-col>
              <el-col :span="4">
                <h3 style="padding-left: 0; margin-left: -8px;">性别</h3>
              </el-col>
              <el-col :span="8">
                <h3 style="padding-left: 20px;">手机号</h3>
              </el-col>
            </el-row>
          </template>
          <el-option v-for="item in remoteMemberData" :key="item.id" :label="item.name" :value="item.id">
            <el-row align="middle">
              <el-col :span="5" style="padding-left: 12px;">{{ item.id }}</el-col>
              <el-col :span="7" style="padding-left: 20px;">{{ item.name }}</el-col>
              <el-col :span="4" style="padding-left: 4px;">{{ item.gender }}</el-col>
              <el-col :span="8" style="padding-left: 16px;">{{ item.tel }}</el-col>
            </el-row>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 课时卡选择 -->
      <el-form-item label="课时卡选择" prop="cardId">
        <el-select v-model="cardForm.cardId" placeholder="-请选择绑定的课时卡-" size="large" style="width: 100%"
          :loading="cardListLoading">
          <el-option v-for="item in classCards" :key="item.cardId" :label="item.cardName" :value="item.cardId" />
        </el-select>
      </el-form-item>

      <!-- 充值次数 -->
      <el-form-item label="充值次数">
        <el-input-number v-model="cardForm.validCount" :min="1" controls-position="right" class="w50" />
      </el-form-item>

      <!-- 有效期 -->
      <el-form-item label="有效期">
        <el-input-number v-model="cardForm.validDay" :min="1" controls-position="right" class="w50" />
      </el-form-item>

      <!-- 实收金额 -->
      <el-form-item label="实收金额" prop="receivedMoney">
        <el-input v-model="cardForm.receivedMoney" placeholder="金额" class="w50">
          <template #prepend>￥</template>
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <!-- 支付方式 -->
      <el-form-item label="支付方式" prop="payMode">
        <el-select v-model="cardForm.payMode" placeholder="-请选择支付方式-" size="large" style="width: 100%">
          <el-option v-for="item in selectList.payModeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注">
        <el-input v-model="cardForm.note" type="textarea" />
      </el-form-item>

      <!-- 按钮 -->
      <el-form-item>
        <el-button type="danger" @click="bindConfirm(memberBindRef)">确认</el-button>
        <el-button type="success" @click="cancelForm">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { fetchClassCards, addClassCard } from '@/api/classCardApi.js'
import axios from 'axios'

// 表单引用和数据
const memberBindRef = ref()
const cardForm = reactive({
  memberId: '',
  cardId: '',
  validCount: 50,
  validDay: 30,
  receivedMoney: '',
  payMode: '',
  note: ''
})

// 表单校验规则
const rules = reactive({
  cardId: [{ required: true, message: '请选择课时卡', trigger: 'change' }],
  receivedMoney: [{ required: true, message: '请输入支付金额', trigger: 'blur' }],
  payMode: [{ required: true, message: '请选择付款方式', trigger: 'change' }]
})

// 支付方式列表
const selectList = reactive({
  payModeList: [
    { value: '1', label: '支付宝' },
    { value: '2', label: '微信' },
    { value: '3', label: '现金' },
    { value: '4', label: '银行卡' }
  ]
})

// 课时卡数据
const classCards = ref([])
const cardListLoading = ref(false)

const loadClassCards = async () => {
  cardListLoading.value = true
  try {
    const res = await axios.get('http://localhost:8080/api/class-cards')  // ✅ 加载最新数据
    classCards.value = res.data
  } catch (err) {
    ElMessage.error('加载课时卡失败')
  } finally {
    cardListLoading.value = false
  }
}

onMounted(() => {
  loadClassCards()
})

const bindConfirm = async (formE) => {
  if (!formE) return
  formE.validate(async (valid) => {
    if (valid) {
      try {
        await ElMessageBox.confirm('你确定要绑定吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const now = new Date().toISOString()

        const newCardData = {
          cardId: cardForm.cardId,
          studentId: cardForm.memberId,
          cardName: classCards.value.find(c => c.cardId === cardForm.cardId)?.cardName || '',
          cardType: 'normal',
          totalClasses: cardForm.validCount,
          remainingClasses: cardForm.validCount,
          price: Number(cardForm.receivedMoney),
          startDate: new Date().toISOString().split('T')[0],  // ✅ 当前日期
          expireDate: calculateExpireDate(cardForm.validDay),
          isNotified: false,
          createTime: now,
          updateTime: now,
          payMode: cardForm.payMode,
          note: cardForm.note
        }

        await addClassCard(newCardData)
        ElMessage.success('绑定课时卡成功')

        await loadClassCards()  // ✅ 刷新最新课时卡数据

      } catch (err) {
        if (err !== 'cancel') {
          console.error(err)
          ElMessage.error('绑定失败')
        } else {
          ElMessage.info('取消操作')
        }
      }
    }
  })
}

function calculateExpireDate(validDay) {
  const date = new Date()
  date.setDate(date.getDate() + validDay)
  return date.toISOString().split('T')[0]
}

const cancelForm = () => {
  // 重置表单
  Object.assign(cardForm, {
    memberId: '',
    cardId: '',
    validCount: 50,
    validDay: 30,
    receivedMoney: '',
    payMode: '',
    note: ''
  })
}

const loading = ref(false)
const remoteMemberData = ref([])

const remoteMethod = async (query) => {
  if (!query) return
  loading.value = true
  try {
    const res = await axios.get('http://localhost:8080/api/students')
    const all = Array.isArray(res.data) ? res.data : res.data.data
    remoteMemberData.value = all
      .filter(item => item.name.includes(query) || item.contactPhone.includes(query))
      .map(item => ({
        id: item.studentId,
        name: item.name,
        gender: item.gender === 'M' ? '男' : item.gender === 'F' ? '女' : '',
        tel: item.contactPhone
      }))
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="less">
.w50 {
  width: 45%;
}
</style>
